const fs = require('fs');
const path = require('path');
const args = require('minimist')(process.argv.slice(2))

const helpStr = String.raw`node .\change_extension.js --path=<PATH TO DIR> --from=[txt] --to=[dat] --lv=[1]`;

if(args['path']){
  dir = args['path'];
}else{
 console.log(helpStr);
 process.exit();
}

if(args['from']){
  from = `.${args['from']}`
}
else{
  from = ".txt";
}

if(args['to']){
  to = `.${args['to']}`
}
else{
  to = ".dat";
}

if(args['lv']){
  lv = parseInt(args['lv']);
}
else{
  lv = 1;
}

findFiles(dir, lv);

function findFiles(dir, lv){
  dirents = fs.readdirSync(dir, { withFileTypes: true });
  console.log(dirents, lv)
  dirents.forEach(dirent => { 

    if (!dirent.isDirectory() && path.extname(dirent.name) === from) {
      doChange(dir, dirent.name);
    }
    
    if(lv > 1 && dirent.isDirectory()){
      findFiles(path.join(dir,dirent.name), lv-1)
    }
  })
}

function doChange(dir, file){
  newname  = path.basename(file, from) + to; 
  fs.renameSync(path.join(dir, file), path.join(dir, newname));
  console.log(`rn:${path.join(dir, file)} ==> ${path.join(dir, newname)}`);
}

